<template>
  <div>
    <div class="search">
      <Row>
        <Col>
          <Card>
            <Row>
              <Form ref="searchForm" :model="searchForm" inline :label-width="70" class="search-form">
                <Form-item label="物料名称" prop="">
                  <Select v-model="searchForm.pre_code" clearable filterable style="width:267px">
                    <Option v-for="(item,index) in materialNameList" :value="item.pre_code" :key="index">
                      {{ item.name }} 
                    </Option>
                  </Select>
                </Form-item>
                <Form-item style="margin-left:-35px;" class="br">
                  <Button @click="handleSearch" type="primary" icon="ios-search">搜索</Button>
                  <Button @click="handleReset">重置</Button>
                </Form-item>
              </Form>
            </Row>
            <Row class="operation">
              <Button @click="add" type="primary" icon="md-add" >新增物料</Button>
              <Button @click="refresh" icon="md-sync">刷新</Button>
            </Row>
            <Row>
              <Alert show-icon>
                已选择 <span class="select-count">{{selectCount}}</span> 项
                <a class="select-clear" @click="clearSelectAll">清空</a>
              </Alert>
            </Row>
            <Row>
              <Table
                border
                :loading="loading"
                :columns="columns"
                :data="data"
                sortable="custom"
                @on-selection-change="showSelect"
                ref="table">
              </Table>
            </Row>
            <Row type="flex" justify="end" class="page">
              <Page
                :current="searchForm.pageNumber"
                :total="total"
                :page-size="searchForm.pageSize"
                @on-change="changePage"
                @on-page-size-change="changePageSize"
                :page-size-opts="[10,20,50]"
                size="small"
                show-total
                show-elevator
                show-sizer
              ></Page>
            </Row>
          </Card>
        </Col>
      </Row>
      <!-- 新增物料窗体 -->
      <Modal title="新增物料" v-model="newMaterialVisible" :mask-closable='false' :width="500" :styles="{top: '200px'}">
        <Form ref="newMaterialForm" :model="newMaterialForm" :label-width="100" :rules="newMaterialFormValidate">
          <Form-item label="物料分类" prop="type">
            <Select v-model="newMaterialForm.type" style="width:300px" >
              <Option value="设备">设备</Option>
              <Option value="主材">主材</Option>
            </Select>
          </Form-item>
          <Form-item label="物料名称" prop="material_name_id">
            <Select v-model="newMaterialForm.material_name_id" clearable filterable style="width:300px" @on-change="changeMaterialName">
              <Option v-for="(item,index) in materialNameList" :value="item.id" :key="index">
                {{ item.name }}
              </Option>
            </Select>
          </Form-item>
          <FormItem label="物料编码" prop="code">
              <Input v-model="newMaterialForm.code" style="width:300px" />
          </FormItem>
          <FormItem label="规格型号" prop="stype">
              <Input v-model="newMaterialForm.stype" style="width:300px" />
          </FormItem>
          <FormItem label="计量单位" prop="unit">
              <Input v-model="newMaterialForm.unit" style="width:300px" />
          </FormItem>
          <FormItem label="含税单价" prop="tax_price">
              <Input v-model="newMaterialForm.tax_price" style="width:300px" />
          </FormItem>
          <FormItem label="单体重量(kg)" prop="weight">
              <Input v-model="newMaterialForm.weight" style="width:300px" />
          </FormItem>
        </Form>
        <div slot="footer">
          <Button type="text" @click="cancelMaterial">取消</Button>
          <Button type="primary" @click="submitAddMaterial">提交</Button>
        </div>
      </Modal>
      <!-- 编辑物料窗体 -->
      <Modal title="编辑物料" v-model="editMaterialVisible" :mask-closable='false' :width="500" :styles="{top: '200px'}">
        <Form ref="editMaterialForm" :model="editMaterialForm" :label-width="100" :rules="newMaterialFormValidate">
          <Form-item label="物料分类" prop="type">
            <Select v-model="newMaterialForm.type" style="width:300px" >
              <Option value="设备">设备</Option>
              <Option value="主材">主材</Option>
            </Select>
          </Form-item>
          <Form-item label="物料名称">
                {{ this.editMaterialForm.name }}
          </Form-item>
          <FormItem label="物料编码" prop="code">
              {{ this.editMaterialForm.code }}
          </FormItem>
          <FormItem label="规格型号" prop="stype">
              {{ this.editMaterialForm.stype }}
          </FormItem>
          <FormItem label="计量单位" prop="unit">
              <Input v-model="editMaterialForm.unit" style="width:300px" />
          </FormItem>
          <FormItem label="含税单价" prop="tax_price">
              <Input v-model="editMaterialForm.tax_price" style="width:300px" />
          </FormItem>
          <FormItem label="单体重量(kg)" prop="weight">
              <Input v-model="editMaterialForm.weight" style="width:300px" />
          </FormItem>
        </Form>
        <div slot="footer">
          <Button type="text" @click="cancelMaterial">取消</Button>
          <Button type="primary" @click="submitEditMaterial">提交</Button>
        </div>
      </Modal>
    </div>
  </div>
</template>
<script>
import util from '@/libs/util';
import { getAllMaterialName, getMaterialList, getMaterialNameById, checkMaterialCode, insertMaterial, editMaterial } from '@/api/material';
export default {
  data() {
    const validateMaterialName = (rule, value, callback) => {
      if (!value) {
        callback(new Error('物料名称必须选择'))
      } else {
        callback();
      }
    };
    return {
      loading: false,
      newMaterialVisible: false,
      editMaterialVisible: false,
      materialNameList: [],
      searchForm: {
        pre_code: '',
        pageNumber: 1,
        pageSize: 10,
      },
      newMaterialForm: {
        material_name_id: 0,
        type: '设备',
        base_code: '',
        code: '',
        name: '',
        stype: '',
        unit: '',
        tax_price: 0.00,
        weight: 0.0
      },
      editMaterialForm: {
          id: 0,
          type: '',
          code: '',
          name: '',
          stype: '',
          unit: '',
          tax_price: 0.00,
          weight: 0,
        },
      newMaterialFormValidate: {
        name: [
          {validator: validateMaterialName, trigger: "blur"}
        ],
        code: [
          {required: true, message: "物料编码不能为空", trigger: "blur"}
        ],
        stype: [
          {required: true, message: "规格型号不能为空", trigger: "blur"}
        ],
        unit: [
          {required: true, message: "单位不能为空", trigger: "blur"}
        ]
      },
      data: [],
      total: 0,
      selectCount: 0,
      selectList: [],
      exportData: [],
      columns: [
        {
            type: "selection",
            width: 50,
            align: "center",
            fixed: "left"
          },
          {
            type: "index",
            width: 50,
            align: "center",
            fixed: "left"
          },
          {
            title: '分类',
            key: 'type',
            align: "center",
            width: 60
          },
          {
            title: '物料编码',
            key: 'code',
            align: "center",
            width: 100
          },
          {
            title: '物料名称',
            key: 'name',
            width: 140
          },
          {
            title: '规格型号',
            key: 'stype',
            width: 140
          },
          {
            title: '单位',
            key: 'unit',
            align: "center",
            width: 60
          },
          {
            title: '含税单价(元)',
            key: 'tax_price',
            align: "right",
            width: 120
          },
          {
            title: '单体重量(kg)',
            key: 'weight',
            align: "right",
            width: 120
          },
          {
            title: '运输类别',
            key: 'discription',
            width: 160
          },
          {
            title: "状态",
            key: "is_active",
            align: "center",
            width: 80,
            render: (h, params) => {
              let re = "";
              if (params.row.is_delete === 0) {
                return h("div", {style: { color: 'green'}}, '启用');
              } else {
                return h("div", {style: { color: 'red'}}, '禁用');
              }
            }
          },
          {
            title: '操作',
            key: 'action',
            width: 180,
            align: 'center',
            render: (h, params) => {
              let reDisable = "";
              if (params.row.is_delete === 1) {
                reDisable = "启用";
              } else {
                reDisable = "禁用";
              }
              return h('div', [
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.edit(params.row)
                    }
                  }
                }, '编辑'),
                h('Button', {
                  props: {
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.disable(params.row)
                    }
                  }
                }, reDisable)
              ]);
            }
          }
        ],
    }
  },
  methods: {
    // 获取所有物料名称
    getMaterialNameList() {
      getAllMaterialName().then(res => {
        if (res.code === 0) {
          this.materialNameList = res.data.raws;
        }
      })
    },
    // 分页获取物料清单
    getMaterialList() {
      this.loading = true;
      getMaterialList(this.searchForm).then(res => {
        if (res.code === 0) {
          this.data = res.data.raws;
          this.total = res.data.count;
        }
        this.loading = false;
      })
    },
    init() {
      this.getMaterialNameList();
      this.getMaterialList()
    },
    changePage(v) {
      this.searchForm.pageNumber = v;
      this.getMaterialList();
    },
    changePageSize(v) {
      this.searchForm.pageSize = v;
      this.getMaterialList();
    },
    handleSearch() {
      if (this.searchForm.pre_code.trim() !== '') {
        this.searchForm.pageNumber = 1;
        this.getMaterialList();
      } else {
        this.$Message.info('请选择材料名称');
        return;
      }
    },
    handleReset() {
      this.$refs.searchForm.resetFields();
      this.searchForm.pre_code = '';
      this.searchForm.pageNumber = 1;
      this.searchForm.pageSize = 10;
      this.getMaterialList();
    },
    refresh() {
      this.getMaterialList();
    },
    showSelect(e) {
      this.exportData = e;
      this.selectList = e;
      this.selectCount = e.length;
    },
    clearSelectAll() {
      this.$refs.table.selectAll(false);
    },
    add() {
      const hasPermission = util.oneOf('add', this.$route.meta.permTypes);
      if (!hasPermission) {
        this.$Message.error('抱歉，您没有操作权限！');
        return;
      };
      this.$refs.newMaterialForm.resetFields();
      this.newMaterialVisible = true;
    },
    edit(v) {
      const hasPermission = util.oneOf('edit', this.$route.meta.permTypes);
      if (!hasPermission) {
        this.$Message.error('抱歉，您没有操作权限！');
        return;
      };
      this.editMaterialForm.id = v.id;
      this.editMaterialForm.type = v.type;
      this.editMaterialForm.code = v.code;
      this.editMaterialForm.name = v.name;
      this.editMaterialForm.stype = v.stype;
      this.editMaterialForm.unit = v.unit;
      this.editMaterialForm.tax_price = v.tax_price;
      this.editMaterialForm.weight = v.weight;
      this.editMaterialVisible = true;
    },
    disable(v) {
      const hasPermission = util.oneOf('disable', this.$route.meta.permTypes);
      if (!hasPermission) {
        this.$Message.error('抱歉，您没有操作权限！');
        return;
      };
      this.editMaterialForm.id = v.id;
      this.editMaterialForm.type = v.type;
      this.editMaterialForm.code = v.code;
      this.editMaterialForm.name = v.name;
      this.editMaterialForm.stype = v.stype;
      this.editMaterialForm.unit = v.unit;
      this.editMaterialForm.tax_price = v.tax_price;
      if (v.weight) {
        this.editMaterialForm.weight = v.weight;
      } else {
        this.editMaterialForm.weight = 0;
      }
      if (v.is_delete === 1) {
        this.editMaterialForm.is_delete = 0;
      } else {
        this.editMaterialForm.is_delete = 1;
      }
      editMaterial(this.editMaterialForm).then(res => {
        if (res.code === 0) {
          this.$Message.success(res.message);
          this.getMaterialList();
        }
      });
    },
    changeMaterialName(value) {
      if (value) {
        getMaterialNameById({id: value}).then(res => {
          if (res.code === 0) {
            this.newMaterialForm.material_name_id = res.data.id;
            this.newMaterialForm.base_code = res.data.pre_code;
            this.newMaterialForm.code = res.data.pre_code;
            this.newMaterialForm.name = res.data.name;
          }
          
        })
      }
    },
    cancelMaterial() {
      this.newMaterialVisible = false;
      this.editMaterialVisible = false;
    },
    submitAddMaterial() {
      this.$refs.newMaterialForm.validate(valid => {
        if (valid) {
          if (isNaN(this.newMaterialForm.tax_price) || isNaN(this.newMaterialForm.weight)) {
            this.$Message.error('金额（重量）必须是一个有效的数字');
            return;
          }
          checkMaterialCode({code: this.newMaterialForm.code}).then(res => {
            if (res.data) {
              insertMaterial(this.newMaterialForm).then(res => {
                if (res.code === 0) {
                  this.$Message.success(res.message);
                  this.newMaterialVisible = false;
                  this.getMaterialList();
                }
              })
            } else {
              this.$Message.error('此物料已经存在，不能重复添加');
              return;
            }
          })
        }
      })
    },
    submitEditMaterial() {
      if (isNaN(this.editMaterialForm.tax_price) || isNaN(this.editMaterialForm.weight)) {
        this.$Message.error('金额（重量）必须是一个有效的数字');
        return;
      }
      editMaterial(this.editMaterialForm).then(res => {
        if (res.code === 0) {
          this.$Message.success(res.message);
          this.editMaterialVisible = false;
          this.getMaterialList();
        }
      })
    }
  },
  mounted() {
    this.init();
  }
}
</script>
<style lang="less">
  @import "./materialManager.less";
</style>